﻿var VMFormData = function (data) {
    if (!data 
        || !data.ItemMetadata 
        || !data.FormData 
        || !data.FormData.ItemData) {
        return;
    }
    var me = this;
    var metadata = data.ItemMetadata;
    var tableName = data.FormData.FormName;
    var richEditors = {};
    var isOnly = true;
    $(function () {
        if (data.ExceptionMessage != null) {
            document.clear();
            document.body.innerHTML = data.ExceptionMessage;
        }

        if (data.FormData.FlowTemplateID > 0) {
            var formSystemNextOwner = "#form" + tableName + "_SystemNextOwner";
            var formSystemReadOwner = "#form" + tableName + "_SystemReadOwner";
            // 把用户选择的转换中的待办待阅角色传给相应控件
            $("input:radio[name='transformation']").change(function () {
                //编辑前清空待办待阅
                me.clearToDoAndToRead();
                var systemNextOwner = $(formSystemNextOwner);
                if (systemNextOwner.length > 0) {
                    var toDoRoleID = $("input:radio[name='transformation']:checked").attr("todorole");
                    $(formSystemNextOwner).combobox("options").roleID = toDoRoleID;
                    if (toDoRoleID.length > 0) {
                        systemNextOwner.combobox('exEnable');
                    } else {
                        systemNextOwner.combobox('exDisable');
                    }
                }

                var systemReadOwner = $(formSystemReadOwner);
                if (systemReadOwner.length > 0) {
                    var toReadRoleID = $("input:radio[name='transformation']:checked").attr("toreadrole");
                    $(formSystemReadOwner).combobox("options").roleID = toReadRoleID;
                    if (toReadRoleID.length > 0) {
                        systemReadOwner.combobox('exEnable');
                    } else {
                        systemReadOwner.combobox('exDisable');
                    }
                }
            });
            //编辑前清空待办待阅
            me.clearToDoAndToRead();

            // 只有一个转换条件时默认选中
            var flowTransList = $("input:radio[name='transformation']");
            if (flowTransList.length == 1) {
                flowTransList[0].click();
            } else if (flowTransList.length > 0) {
                var systemNextOwner = $(formSystemNextOwner);
                if (systemNextOwner.length > 0) {
                    systemNextOwner.combobox('exDisable');
                }
                var systemReadOwner = $(formSystemReadOwner);
                if (systemReadOwner.length > 0) {
                    systemReadOwner.combobox('exDisable');
                }
            }
        }

        // 查看页面初始化富文本框
        if (data.FormData.FormDisable) {
            for (var itemName in metadata) {
                var itemMeta = metadata[itemName];
                if (itemMeta.IsRichText) {
                    eval('viewModel.form.' + itemName + '(amCommon.htmlDecode(viewModel.form.' + itemName + '()))');
                }
            }
        }
    });

    // 在编辑的时候把待办人和抄送人清空
    this.clearToDoAndToRead = function () {
        if (viewModel.form) {
            if (viewModel.form.SystemNextOwner) {
                viewModel.form.SystemNextOwner("");
            }
            if (viewModel.form.SystemReadOwner) {
                viewModel.form.SystemReadOwner("");
            }
        }
    }

    // 提交前事件
    this.fBeforeSubmit = undefined;

    // 附加验证规则
    this.fExtraValidation = undefined;

    this.gridEditors = {};
    this.form = ko.mapping.fromJS(data.FormData.ItemData);
    this.paramNewUrl = "/api/FormData/New?FormID=" + data.FormData.FormID;
    this.paramUpdateUrl = "/api/FormData/Update?FormID=" + data.FormData.FormID;

    this.submitClick = function () {
        alert("11111"); return false;
        if (!isOnly) { 
            return false;
        }
       
        // 执行提交前事件
        if (me.fBeforeSubmit && typeof (me.fBeforeSubmit) == "function") {
            if (me.fBeforeSubmit() == false) {
                isOnly = true;
                return false;
            }
        }

        // 处理富文本框
        for (var itemName in richEditors) {
           
            var itemEditor = richEditors[itemName];
            itemEditor.sync();
            eval('viewModel.form.' + itemName + '(amCommon.htmlEncode(itemEditor.html()))');
        }
       
        var validate = $("form").form("validate");
        if (!validate) {
            return false;
        }

        if (!data.FormData) {
            $.messager.alert('错误', "参数错误！", 'error');
            return false;
        }

        // 子表
        if (data.FormData.ChildData) {
            for (var child in data.FormData.ChildData) {
                if (me.gridEditors[child]) {
                    if (!me.gridEditors[child].validData()) {
                        return false;
                    }
                }
            }
        }

        // 执行附加验证规则
        if (me.fExtraValidation && typeof (me.fExtraValidation) == "function") {
            if (me.fExtraValidation() == false) {
                return false;
            }
        }

        // 若走工作流，则检查是否有选择转换
        var flowStatusID = -1;
        if (data.FormData.FlowTemplateID > 0) {
            var transformationValue = $("input:radio[name='transformation']:checked").val();
            if (transformationValue == null) {
                $.messager.alert('提示', "请先选择处理方式！", "error");
                return false;
            }
            else {
                flowStatusID = transformationValue;
            }
        }

        if (data.FormData.ChildData) {
            for (var child in data.FormData.ChildData) {
                if (me.gridEditors[child]) {
                    var changes = me.gridEditors[child].getChanges();
                    $.extend(data.FormData.ChildData[child], changes);
                }
            }
        }

        var url = me.paramNewUrl;
        if (data.FormData.RecordID > 0) {
            url = me.paramUpdateUrl;
        }

        if (flowStatusID > 0) {
            data.FormData.NewFlowStatusID = flowStatusID;
        }
     
        data.FormData.ItemData = ko.toJS(me.form);
        // 执行提交事件
        if (me.fOnSubmit && typeof (me.fOnSubmit) == "function") {
            if (me.fOnSubmit() == false) {
                return false;
            }
        }
        isOnly = false;
        $.ajax({
            type: "POST",
            url: url,
            data: ko.toJSON(data.FormData),
            contentType: "application/json"
        })
        .success(function (result, status,error) {
            isOnly = true;

            if (result > 0) {
                if (url == "/api/LBProductLableSet/AddText" || url == "/api/LBProductLableSet/Add") {
                    alert('数据后台生成中...');
                    
                 location.href = "/User/LBProductLableSet/Export";
                    //top.closeDialog();
                  
                    return;
                }
                top.closeRefreshDialog(result);
            }
            else if (result <= 0) {
                $.messager.alert('提示', '很抱歉，操作出现异常！请联系管理员。', 'error');
            }
            else {
               
                $.messager.alert('提示', result, 'error');
            }
        })
        .error(function (result) {
            isOnly = true;
            var message = '很抱歉，操作出现异常！请联系管理员。';
            if (result) {
                if ($("#load") != undefined || $("#load") != null) {
                    $("#load").css("display", "none");
            }
              
                if (result.responseJSON && result.responseJSON.ExceptionMessage) {
                    message = result.responseJSON.ExceptionMessage;
                }
                else if (result.responseText) {
                    message = result.responseText;
                }
            }
            
            $.messager.alert('错误', message.replace("-10",""), 'error');
        });
    };

    this.getSerialLength = function (serialNumbers) {
        var result = 0;
        if (!amCommon.isArray(serialNumbers)) {
            return result;
        }

        if (serialNumbers.length == 1 && amCommon.notEmpty(serialNumbers[0])) {
            // 避免误把多个序列号视为一个字符串的情况
            serialNumbers = serialNumbers[0].toString().split(',');
        }

        // 移除空值
        return serialNumbers.removeEmpty().length;
    };

    this.disableEditor = function (fieldName) {
        var formName = data.FormData.FormName;

        if (!amCommon.notEmpty(formName) || !amCommon.notEmpty(fieldName)) {
            return;
        }
        var control = $('#form' + formName + '_' + fieldName);
        if (!control || control.length <= 0) {
            return;
        }

        var options = control.attr("data-options");
        if (amCommon.notEmpty(options) && options.trimEnd) {
            options = options.trimEnd(',') + ',' + 'disabled:true';
        }
        else {
            options = 'disabled:true';
        }

        control.attr("data-options", options);
    };

    this.addDateValid = function (fieldName, validationRule, compareFieldName) {
        var formName = data.FormData.FormName;

        if (!amCommon.notEmpty(validationRule) || !amCommon.notEmpty(formName) || !amCommon.notEmpty(compareFieldName)
            || !metadata || !metadata[compareFieldName]) {
            return;
        }

        var compareFieldDisplayName = metadata[compareFieldName].DisplayName;
        var control = $('#form' + formName + '_' + fieldName);
        if (!control || control.length <= 0 || !amCommon.notEmpty(compareFieldDisplayName)) {
            return;
        }

        var newValid = validationRule + '["' + compareFieldName + '","' + compareFieldDisplayName + '"]';
        var currentValid = control.attr("validtype");
        if (amCommon.notEmpty(currentValid)) {
            currentValid = currentValid + '&&' + newValid;
        }
        else {
            currentValid = newValid;
        }

        control.attr("validtype", currentValid);
    };

    // 编辑页面初始化富文本框
    if (!data.FormData.FormDisable && 'KindEditor' in window) {
        KindEditor.ready(function (K) {
            for (var itemName in metadata) {
                var itemMeta = metadata[itemName];
                if (itemMeta.IsRichText) {
                    eval('viewModel.form.' + itemName + '(amCommon.htmlDecode(viewModel.form.' + itemName + '()))');
                    richEditors[itemName] = K.create('#form' + (tableName ? tableName : '') + '_' + itemName, {
                        cssPath: '/Scripts/kindeditor/plugins/code/prettify.css',
                        uploadJson: '/Scripts/kindeditor/upload_json.ashx',
                        fileManagerJson: '/Scripts/kindeditor/file_manager_json.ashx'
                    });
                }
            }
        });
    }
};